package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 课程分类Service
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {
    private final CourseCategoryMapper courseCategoryMapper;

    public CourseCategoryServiceImpl(CourseCategoryMapper courseCategoryMapper) {
        this.courseCategoryMapper = courseCategoryMapper;
    }

    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes() {
        List<CourseCategory> courseCategorieList = courseCategoryMapper.selectList(Wrappers.<CourseCategory>query().orderByAsc("id"));
        List<CourseCategoryTreeDto> root = new ArrayList<>();
        Map<String, CourseCategoryTreeDto> courseCategoryMap = new HashMap<>();
        for (CourseCategory courseCategory : courseCategorieList) {
            CourseCategoryTreeDto convert = CourseCategoryTreeDto.convert(courseCategory);
            if (StringUtils.equals(courseCategory.getParentid(), "1")) {
                root.add(convert);
            }
            courseCategoryMap.put(courseCategory.getId(), convert);
        }
        for (CourseCategory courseCategory : courseCategorieList) {
            if (!StringUtils.equals(courseCategory.getParentid(), "1")) {
                CourseCategoryTreeDto parentTreeNode = courseCategoryMap.get(courseCategory.getParentid());
                if (Objects.isNull(parentTreeNode)) {
                    continue;
                }
                parentTreeNode.addChild(CourseCategoryTreeDto.convert(courseCategory));
            }
        }
        return root;
    }
}
